<template>
  <div class="flex-row">
    <div style="margin-right: 10px;">
      <el-tree :data="data" :props="defaultProps" style="width: 12rem" @node-click="handleNodeClick">
      </el-tree>
    </div>

    <div>
      <el-col class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="filters">
          <el-form-item class="mb-10">
            <el-input size="small" v-model="filters.name" placeholder="设备名称"></el-input>
          </el-form-item>
          <el-form-item class="mb-10">
            <el-input size="small" v-model="filters.name" placeholder="设备编码"></el-input>
          </el-form-item>
          <el-form-item class="mb-10">
            <el-button size="small" type="danger" @click="getAllDevice">查询</el-button>
          </el-form-item>
          <el-form-item class="mb-10">
            <el-button size="small" type="success" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </el-col>


      <el-table :data="deviceData" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
        style="width: 100%;">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column type="index" label="序号" min-width="60">
        </el-table-column>
        <el-table-column prop="name" label="设备名称" min-width="120" sortable>
        </el-table-column>
        <el-table-column prop="netStr" label="所属网关" min-width="100" sortable>
        </el-table-column>
        <el-table-column prop="deviceTypeStr" label="所属型号" min-width="100" sortable>
        </el-table-column>
        <el-table-column prop="factoryRoom" label="设备车间" min-width="100" sortable>
        </el-table-column>
        <el-table-column prop="factoryBranch" label="设备分厂" min-width="100" sortable>
        </el-table-column>
        <el-table-column prop="factoryMain" label="设备工厂" min-width="100" sortable>
        </el-table-column>
        <el-table-column label="操作" width="380">
          <template slot-scope="scope">
            <el-button size="small" type="warning" @click="handleConf(scope.$index, scope.row)">设置报警阈值</el-button>
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDel(scope.$index, scope.row)">删除</el-button>
            <el-button size="small" type="primary" @click="seeTipPerson(scope.row)">查看报警人</el-button>
          </template>
        </el-table-column>
      </el-table>


   <div class="block">
      <el-pagination style="text-align: right;" background layout="total,prev, pager, next"
        :current-page="pageNo" @current-change="handleCurrentChange" :page-size="pageSize" :total="total"></el-pagination>
    </div>


<!--      <el-col :span="24" class="toolbar">
        <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
        <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="20" :total="total"
          style="float:right;">
        </el-pagination>
      </el-col> -->

    </div>




    <!--编辑界面-->
    <el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="100px" :rules="editFormRules" ref="editForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="起始地址">
          <el-input v-model="editForm.addr" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="在网关的顺序">
          <el-input v-model="editForm.netOrder" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属型号">
          <el-select v-model="editForm.deviceTypeId" placeholder="请选择设备类型">
             <el-option
               v-for="item in deviceTypes"
               :key="item.id"
               :label="item.name"
               :value="item.id">
             </el-option>
           </el-select>
        </el-form-item>
        <el-form-item label="所属网关">
          <el-select v-model="editForm.netId" placeholder="请选择设备类型">
             <el-option
               v-for="item in nets"
               :key="item.id"
               :label="item.name"
               :value="item.id">
             </el-option>
           </el-select>
        </el-form-item>
        <el-form-item label="报警规则">
          <el-radio-group class="flex-column-between" v-model="editForm.warnModel">
              <el-radio :label="0">模式一：即刻触发报警</el-radio>
              <el-radio :label="1">模式二：超过阈值时长3分钟以上报警 或 超过阈值累积5次以上报警</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="所属模块">
          <el-select v-model="editForm.moduleId" placeholder="请选择模块">
            <el-option v-for="item in moduleList" :key="item.id" :label="item.title" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="success" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--新增界面-->
    <el-dialog title="新增" :visible.sync='addFormVisible' :close-on-click-modal="false" @close="beforeClose">
      <el-form :model="addForm" label-width="100px" :rules="addFormRules" ref="addForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="起始地址">
          <el-input v-model="addForm.addr" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="在网关的顺序">
          <el-input v-model="addForm.netOrder" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属型号">
          <el-select v-model="deviceTypeId" placeholder="请选择设备类型">
             <el-option
               v-for="item in deviceTypes"
               :key="item.id"
               :label="item.name"
               :value="item.id">
             </el-option>
           </el-select>
        </el-form-item>
        <el-form-item label="所属网关">
          <el-select v-model="netId" placeholder="请选择设备类型">
             <el-option
               v-for="item in nets"
               :key="item.id"
               :label="item.name"
               :value="item.id">
             </el-option>
           </el-select>
        </el-form-item>
        <el-form-item label="报警规则">
          <el-radio-group class="flex-column-between" v-model="addForm.warnModel">
              <el-radio :label="0">模式一：即刻触发报警</el-radio>
              <el-radio :label="1">模式二：超过阈值时长3分钟以上报警 或 超过阈值累积5次以上报警</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="所属模块">
          <el-select v-model="addForm.moduleId" placeholder="请选择模块">
            <el-option v-for="item in moduleList" :key="item.id" :label="item.title" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="success" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="查看报警人" width="700px" :visible.sync="is_tip" :close-on-click-modal="false">
      <el-table :data="tipPersonData" border style="width: 100%;">
        <el-table-column prop="temName" label="报警模版" min-width="60">
        </el-table-column>
        <el-table-column prop="phone" label="报警人电话" min-width="60">
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template slot-scope="scope">
            <el-button size="small" @click="editPerson(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="delPerson(scope.$index,scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click.native="addTipPerson">添加报警人</el-button>
      </div>
    </el-dialog>

    <el-dialog title="添加报警人" width="600px" :visible.sync="add_person" border @close="close" :close-on-click-modal="false">
      <el-form :model="personForm" label-width="100px" ref="addForm">
        <el-form-item label="报警模版" prop="name">
          <el-select v-model="personForm.temId" placeholder="请选择报警模版" style="width: 400px;">
             <el-option
               v-for="item in smsTempData"
               :key="item.id"
               :label="item.temName"
               :value="item.id">
             </el-option>
           </el-select>
        </el-form-item>
        <el-form-item label="报警人电话">
          <el-input v-model="personForm.phone" auto-complete="off" style="width: 400px;"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="add_person = false">取消</el-button>
        <el-button type="success" @click.native="personSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
  export default {
    name: 'test2',
    created() {
      this.$store.state.preData = {...this.addForm}
    },
    mounted() {
      this.getAllFactory();
      this.getDeviceTypes();
      this.getNets();
      this.getSmsTemp()
      this.getModule()
    },
    data() {
      return {
        data: [],
        deviceTypeId: '',
        defaultProps: {
          label: 'name',
          children: 'list'
        },
        selectTree: {
          level: '',
          id: ''
        },
        pageNo: 1,
        pageSize: 10,
        deviceTypes: [],
        nets: [],
        netId: '',

        filters: {
          name: ''
        },
        deviceData: [
        ],
        total: 0,
        page: 1,
        listLoading: false,
        sels: [], //列表选中列

        editFormVisible: false, //编辑界面是否显示
        editLoading: false,
        editFormRules: {
          name: [{
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }]
        },
        //编辑界面数据
        editForm: {

        },
        tempList: [],
        addFormVisible: false, //新增界面是否显示
        addLoading: false,
        addFormRules: {
          name: [{
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }]
        },
        //新增界面数据
        addForm: {
          name: '',
          addr:'',
          deviceTypeId: '',
          netId:'',
          netOrder:'',
          warnModel: 0
        },
        is_tip: false,
        smsTempData: [],
        tipPersonData: [],
        is_person: false,
        saveLoading: false,
        add_person: false,
        deviceId: '',
        personForm: {
          deviceId: '',
           temId: '',
           phone: ''
        },
        moduleList: []
      };
    },
    methods: {
      close(){
        this.personForm = {
           temId: '',
           phone: ''
        }
      },
      beforeClose(){
        this.addForm = {...this.$store.state.preData}
      },
      getModule() {
        this.api.get('/work/awbModuleUser/getAllModule').then((res) => {
          this.moduleList = res.data.result;

        });

      },
      getSmsTemp(){
        let params = {
          pageNo: 1,
          pageSize: 10000,
        }
        this.api.get('/work/smsTem/list',{params:params}).then((res) => {
          this.smsTempData = res.data.result.records;
        });
      },
      seeTipPerson(row){
        this.deviceId = row.id
        this.is_tip = true
        this.getPersonList()
      },
      delPerson(index, row) {
        this.$confirm('确认删除该报警人吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          var params = {
            id: row.id
          }
          this.api.post('/work/awbSms/delete', params).then((res) => {
            if(res){
              this.tipPersonData.splice(index,1);
            }
            this.listLoading = false;
            // this.data = res.data.result;

          });

        }).catch(() => {

        });
      },
      addTipPerson(){
        this.add_person = true
        this.personForm.deviceId = this.deviceId
      },
      editPerson(row){
        this.add_person = true
        this.personForm = {
          id: row.id,
          deviceId: row.deviceId,
          temId: row.temId,
          phone: row.phone
        }
      },
      personSubmit(){
        if(!this.personForm.temId){
          this.$message.error('请选择报警模版')
          return
        }
        if(!this.personForm.phone){
          this.$message.error('请填写报警人电话')
          return
        }
        this.saveLoading = true;
        if(!this.personForm.id){
          this.api.post('/work/awbSms/add', this.personForm).then((res) => {
            if(res){
              this.add_person = false;
               this.$message.success('操作成功');
               this.getPersonList();
            }
            this.saveLoading = false;
            // this.data = res.data.result;

          });
        }else{
          this.api.post('/work/awbSms/edit', this.personForm).then((res) => {
            if(res){
              this.add_person = false;
               this.$message.success('操作成功');
               this.getPersonList();
            }
            this.saveLoading = false;
            // this.data = res.data.result;

          });
        }

      },
      getPersonList(){
        var params = {
          deviceId: this.deviceId,
          pageNo: 1,
          pageSize: 10000,
        }
        this.api.get('/work/awbSms/list',{params:params}).then((res) => {
          this.tipPersonData = res.data.result.records;
        });
      },
      saveTipPerson(){

      },
      //获取网关列表
      getNets() {
        var params = {
          pageNo: 1,
          pageSize: this.pageSize,
        }
        this.api.get('/work/awbNet/list',{params:params}).then((res) => {
          this.nets = res.data.result.records;
        });
      },
      //获取deviceType
      getDeviceTypes() {
        var params = {
          pageNo: 1,
          pageSize: this.pageSize,
        }
        this.api.get('/work/awbDeviceType/list',{params: params}).then((res) => {
          this.deviceTypes = res.data.result.records;
        });
      },
      getAllFactory() {
        this.api.get('/work/awbFactory/findFactoryTree').then((res) => {

          this.data = res.data.result;

        });
      },
      handleNodeClick(data, node) {

        this.selectTree.level = node.level;
        this.selectTree.id = data.id;
        this.getAllDevice();
        if (node.level == 3){

        }

      },
      findDeviceById(){
        // var params = {
        //   id: data.id,
        // }
        // console.log(params)
        // findFactoryPersonListByIdApi(params).then((res) => {
        //   console.log(res);

        //   this.users = res.data.result;


        // });
      },


      //获取设备列表
      getAllDevice(data) {
        console.log(data);

        var params = {
          factoryRoom: this.selectTree.id,
          pageNo: this.pageNo,
          pageSize: this.pageSize,
        }
        this.api.get('/work/awbDevice/list',{params:params}).then((res) => {

          this.deviceData = res.data.result.records;
          this.total = res.data.result.total

          for (var i = 0; i < this.deviceData.length; i++) {
            for (var f = 0; f < this.deviceTypes.length; f++) {
              if (this.deviceData[i].deviceTypeId == this.deviceTypes[f].id) {
                // this.deviceData[i].Set('deviceTypeStr',this.deviceTypes[f].name);
                this.deviceData[i]['deviceTypeStr'] = this.deviceTypes[f].name;
              }
            }
            for (var k = 0; k < this.nets.length; k++) {
              if (this.deviceData[i].netId == this.nets[k].id) {
                this.deviceData[i]['netStr'] = this.nets[k].name;
              }
            }
          }

        });

      },
      handleCurrentChange(val) {
        this.pageNo = val;
        this.getAllDevice();
      },
      handleConf: function(index, row) {
        this.$router.push({
          // path: '/deviceConf',
          name: 'deviceConf',
          query: {
            device_id: row.id,
          }
        })
      },
      //删除
      handleDel: function(index, row) {

        this.$confirm('确认删除该设备吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          var params = {
            id: row.id
          }
          this.api.post('/work/awbDevice/delete', params).then((res) => {
            if(res){
              this.deviceData.splice(index,1);
            }
            this.listLoading = false;
            // this.data = res.data.result;

          });

        }).catch(() => {

        });
      },
      //显示编辑界面
      handleEdit: function(index, row) {
        this.editFormVisible = true;
        this.editForm = Object.assign({}, row);
      },
      //显示新增界面
      handleAdd: function() {

        if(this.selectTree.level == 3){
          this.addFormVisible = true;
          // this.addForm = {
          //   name: '',
          //   title: ''

          // };
        }else{
          this.$message('请在厂房下新增设备');
        }


      },
      //编辑
      editSubmit: function() {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.editLoading = true;
              //NProgress.start();
              var params = {
                addr: this.editForm.addr,
                deviceTypeId: this.editForm.deviceTypeId,
                factoryRoom: this.selectTree.id,
                name: this.editForm.name,
                netId: this.editForm.netId,
                netOrder: this.editForm.netOrder,
                warnModel: this.editForm.warnModel,
                moduleId: this.editForm.moduleId,
                id:this.editForm.id
              }
              this.api.post('/work/awbDevice/edit', params).then((res) => {
                if(res){
                  this.editFormVisible = false;
                  this.$message.success('操作成功');
                 // this.data = res.data.result;
                  this.getAllDevice();
                }
                this.editLoading = false;
              });
            });
          }
        });
      },
      //新增
      addSubmit: function() {
        this.$refs.addForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.addLoading = true;

              var params = {
                addr: this.addForm.addr,
                deviceTypeId: this.deviceTypeId,
                factoryRoom: this.selectTree.id,
                name: this.addForm.name,
                netId: this.netId,
                netOrder:this.addForm.netOrder,
                warnModel:this.addForm.warnModel,
                moduleId: this.addForm.moduleId,
              }
              this.api.post('/work/awbDevice/add', params).then((res) => {
                if(res){
                  this.addFormVisible = false;
                  this.$message.success('操作成功');
                  // this.data = res.data.result;
                  this.getAllDevice();
                }
                this.addLoading = false;
              });


            });
          }
        });
      },
      selsChange: function(sels) {
        this.sels = sels;
      },
      //批量删除
      batchRemove: function() {
        var ids = this.sels.map(item => item.id).toString();
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          //NProgress.start();
          let para = {
            ids: ids
          };
          batchRemoveUser(para).then((res) => {
            this.listLoading = false;
            //NProgress.done();
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            // this.getUsers();
          });
        }).catch(() => {

        });
      }
    }

  };
</script>
<style scoped>
  .flex-column-between{
    height: 40px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
</style>
